

/*
 * Copyright (c) 2020. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.evenmo.string;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * This is Description 生产者消费者模式
 * 同步容器，提供put和get方法及getCount方法，
 * 支持2个生产者线程，10个消费者线程
 * @author moyongjun
 * @date 2020/01/05
 */
public class Thread_pro_custom_condition<T>{

final private LinkedList<T> container= new LinkedList<>();

final private int MAX_SIZE=10;//最大容量

    private int count=0;


    private Lock lock= new ReentrantLock();
    private Condition producter =lock.newCondition();
    private Condition consumer= lock.newCondition();

    public  void put(T t){
        try {


        lock.lock();
        while(container.size()==MAX_SIZE){

                producter.await();

        }

        container.add(t);
        count++;
        //通知消费消费
        consumer.signalAll();
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public synchronized T get(){
        lock.lock();
        T t=null;
        try {

            while (container.size() == 0) {
                consumer.await();
            }

            t = container.removeFirst();
            count--;
            //通知生产者生产
            producter.signalAll();
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        return t;
    }

    public static void main(String[] args) {

        Thread_pro_custom_condition tpc=new Thread_pro_custom_condition();

        for (int i = 0; i < 10; i++) {

            new Thread(()->{
                for (int j = 0; j < 5; j++) {
                    System.out.println(Thread.currentThread().getName()+" "+"获取的元素："+tpc.get());

                }
            },"消费者"+i).start();
        }

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        for (int i = 0; i < 2; i++) {

            new Thread(()->{

                for (int j = 0; j < 13; j++) {


                    tpc.put(j);
                }
            },"生产者"+i).start();
        }
    }


}
